package org.seeplnframework.skyeye.log4j.api.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.Filter;
import org.seeplnframework.skyeye.common.constants.SysConstant;
import org.seeplnframework.skyeye.common.util.ConfigUtils;
import org.seeplnframework.skyeye.common.util.HashedWheelTask;
import org.seeplnframework.skyeye.log4j.api.filter.Log4jFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * log4j初始化
 */
@Slf4j
public class Log4jApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        // 初始化配置属性
        ConfigUtils.initProperties(applicationContext);
        // 设置log filter，初始化动作
        Logger logger = Logger.getRootLogger();
        Appender fileAppender = logger.getAppender("FILE");
        fileAppender = fileAppender == null ? logger.getAppender("FILE_INFO") : fileAppender;
        if (fileAppender != null) {
            Filter filter = fileAppender.getFilter();
            if (!(filter instanceof Log4jFilter)) {
                fileAppender.addFilter(new Log4jFilter());
                // 初始化任务调度器
                HashedWheelTask.init();
                // 项目启动后发送欢迎语
                log.error(SysConstant.WELCOME);
            }
        }
    }

}

